package com.agileai.portal.controller.lang;

import java.util.Locale;

import javax.servlet.http.Cookie;

import org.codehaus.jackson.map.ObjectMapper;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.i18n.ResourceBundle;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.model.PersonalFavorite;
import com.agileai.portal.filter.UserCacheManager;

public class PreferSettingHandler extends BaseHandler {

	@PageAction
	public ViewRenderer configLanguage(DataParam param){
		String responseText = FAIL;
		String locale = param.get("locale");
		User user = (User)this.getUser();
		try {
			if (user != null){
				PersonalFavorite personalFavorite = (PersonalFavorite)user.getExtendProperties().get(AttributeKeys.PERSONAL_FAVORITE_OBJECT_KEY);
				personalFavorite.setPreferLocale(locale);
				
				String[] values = locale.split("_");
				if (values != null && values.length == 2){
					String language = values[0];
					String country = values[1];
					
					Locale curlocale = new Locale(language,country);
					user.setLocale(curlocale);
				}
				
				ObjectMapper objectMapper = new ObjectMapper();
				String jsonString = objectMapper.writeValueAsString(personalFavorite);
				
				String userCode = user.getUserCode();
				SecurityGroupManage securityGroupManage = this.lookupService(SecurityGroupManage.class);
				securityGroupManage.updateSecurityUserFavorites(userCode, jsonString);
				
				UserCacheManager userCacheManager = UserCacheManager.getOnly();
				userCacheManager.removeUser(userCode);
			}
			setCookie(locale);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
			responseText = FAIL;
		}
		return new AjaxRenderer(responseText);
	}
	
	private void setCookie(String locale){
		Cookie cookie = new Cookie(ResourceBundle.UserLocaleKey, locale);
		cookie.setMaxAge(-1);		//设为负值，在浏览器内存中保存，关闭浏览器，cookie失效
		cookie.setPath("/");
		response.addCookie(cookie);
	}
}
